<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col
            :md="3"
            :sm="6"
          >
            <a-form-item>
              <a-input
                v-model="queryParam.enterpriseName"
                placeholder="企业名称"
              />
            </a-form-item>
          </a-col>
          <a-col
            :md="3"
            :sm="6"
          >
            <a-form-item>
              <a-select
                v-model="queryParam.status"
                placeholder="企业状态"
                allowClear
                @change="change(queryParam.status)"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option
                  v-for="(value, name) in statusOptions"
                  :key="name"
                  :value="name"
                >
                  {{ value.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col
            :md="3"
            :sm="6"
          >
            <a-form-item>
              <!-- <a-input
                v-model="queryParam.isOpenXbd"
                placeholder="在线支付"
              /> -->
              <a-select
                v-model="queryParam.isOpenXbd"
                placeholder="在线支付"
                allowClear
                @change="change(queryParam.isOpenXbd)"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option
                  v-for="(value, name) in payOptions"
                  :key="name"
                  :value="name"
                >
                  {{ value.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col
            :md="6"
            :sm="8"
          >
            <a-form-item>
              <a-range-picker
                v-model="queryParam.createdTime"
                valueFormat="YYYY-MM-DD"
                :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
              />
            </a-form-item>
          </a-col>
          <a-col
            :md="3"
            :sm="6"
          >
            <span class="table-page-search-submitButtons">
              <a-button
                type="primary"
                @click="$refs.table.refresh(true)"
              >查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="() => queryParam = {}"
              >重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button
        type="primary"
        icon="plus"
        @click="$router.push('/enterprise/add')"
      >新建</a-button>
      <!-- <a-button type="default" icon="download">导出</a-button>
      <a-button type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }} alert</a-button>
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
          <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>-->
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="enterpriseId"
      :columns="columns"
      :data="loadData"
      showPagination="auto"
      :scroll="{ x: true}"
    >
      <!-- <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>-->
      <span
        slot="status"
        slot-scope="text"
      >
        <a-badge
          :status="text | status('enterpriseStatus', 'status')"
          :text="text | status('enterpriseStatus', 'text')"
        />
      </span>
      <span
        slot="description"
        slot-scope="text"
      >
        <ellipsis
          :length="12"
          tooltip
        >{{ text }}</ellipsis>
      </span>
      <span
        slot="feeMode"
        slot-scope="text"
      >
        <span>{{ text === 1 ? '开票金额' : '实发金额' }}</span>
      </span>
      <!-- <span
        slot="feeRate"
        slot-scope="text, record"
      >
        <template v-if="record.feeRateType === 1">
          <span>{{ (record.feeRate * 100).toFixed(2) }}%</span>
        </template>
        <template v-else>
          <a @click="showFeeRate(record)">阶梯费率</a>
        </template>
      </span> -->
      <span
        slot="feeRate"
        slot-scope="text, record"
      >
        <a @click="showFeeRate(record)">点击查看</a>
      </span>
      <span
        slot="isOpenXbd"
        slot-scope="boolean"
      >
        <span>{{ boolean===true?'已开通':'未开通' }}</span>
      </span>
      <span
        slot="createdTime"
        slot-scope="text"
      >{{ text | moment }}</span>

      <span
        slot="action"
        slot-scope="text, record"
      >
        <template>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleSub(record)">{{ record.status === 0 ? '解冻' : '冻结' }}</a>
          <a-divider type="vertical" />
          <a @click="resetLoginPassword(record)">重置登录密码</a>
          <a-divider type="vertical" />
          <a @click="resetPayPasswords(record)">重置支付密码</a>
          <a-divider type="vertical" />
          <a @click="gotoNewPage(record)">进入后台</a>
        </template>

      </span>
    </s-table>
    <create-form
      ref="createModal"
      @ok="handleOk"
    />
    <step-by-step-modal
      ref="modal"
      @ok="handleOk"
    />
    <a-modal
      title="阶梯费率"
      :visible="feeRateVisible"
      :footer="null"
      @cancel="feeRateVisible = false"
    >
      <a-table
        v-show="feeRateRangeList.length"
        :columns="feeRateRangeColumns"
        rowKey="amountLow"
        :pagination="false"
        :data-source="feeRateRangeList"
        size="small"
      >
        <span
          slot="money"
          slot-scope="text"
        >
          <span>{{ text | formatMoney }}</span>
        </span>
        <span
          slot="rate"
          slot-scope="text"
        >
          <span>{{ (text * 100).toFixed(2) }}%</span>
        </span>
      </a-table>
    </a-modal>
    <a-modal
        title="供应商费率"
        :visible="gnflVisible"
        :footer="null"
        @cancel="gnflVisible = false"
        width="800px"
      >
        <a-table
          :columns="FeeRateColumns"
          rowKey="amountLow"
          :pagination="false"
          :data-source="enterpriseServerFeeRateList"
          size="small"
        >
        <span
              slot="feeMode"
              slot-scope="text">
              <template>
                <span v-if="text == 1">开票金额</span>
                <span v-if="text == 2">实发金额</span>
              </template>
            </span>
            <span
              slot="feeRateType"
              slot-scope="text">
              <template>
                <span v-if="text == 1">固定</span>
                <span v-if="text == 2">阶梯</span>
              </template>
            </span>
            <span
              slot="feeRate"
              slot-scope="text, record">
              <template v-if="record.feeRateType == 1">
                <span>{{text}}%</span>
              </template>
              <template v-if="record.feeRateType == 2">
                <a @click="serverName = record.serverName, feeRateGuList = record.feeRateList, showJieti = true">查看</a>
              </template>
            </span>
            <span
              slot="taxRate"
              slot-scope="text">
              <template v-if="text && text != '*'">{{ parseFloat((text*100).toPrecision(12)) }}%</template>
              <template v-else>{{ text}}</template>
            </span>
        </a-table>
      </a-modal>
      <a-modal 
    v-model="showJieti"
    title="阶梯费率"
    @ok="showJieti = false"
    @cancel="showJieti = false"
    width="800px"
    >
    <a-table
            
            :columns="feeRateRangeColumns"
            rowKey="amountLow"
            :pagination="false"
            :data-source="feeRateGuList"
            size="small"
          >
            <span
              slot="money"
              slot-scope="text">
              <span>{{ text | formatMoney }}</span>
            </span>
            <span
              slot="rate"
              slot-scope="text">
              <span>{{ parseFloat((text * 100).toFixed(10)) }}%</span>
            </span>
            <span
              slot="action"
              slot-scope="text, record, index">
              <template v-if="index === 0 || (index + 1) === feeRateRangeList.length">
                <a @click="deleteFeeRangeRow(index)">删除</a>
              </template>
            </span>
          </a-table>
  </a-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import StepByStepModal from '@/modules/StepByStepModal'
import CreateForm from '@/modules/CreateForm'
import { getEnterpriseList, freezeEnterprise, resetLoginPassword, resetPayPassword, getServerFeeList } from '@/api/manage'
import { enterpriseStatus, payStatus } from '@/utils/statusFilters'


export default {
  name: 'TableListPage',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal
  },
  data() {
    return {
      statusOptions: enterpriseStatus,
      payOptions: payStatus,

      mdl: {},
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        // {
        //   title: '#',
        //   scopedSlots: { customRender: 'serial' }
        // },
        {
          title: '企业ID',
          dataIndex: 'enterpriseId',
          width:90,
          align:'center'
        },
        {
          title: '企业名称',
          dataIndex: 'enterpriseName',
          scopedSlots: { customRender: 'description' }
        },
        {
          title: '行业',
          dataIndex: 'industryName'
        },
        {
          title: '用户名',
          dataIndex: 'enterpriseSimpleName'
          // sorter: true
          // needTotal: true,
          // customRender: (text) => text + ' 次'
        },
        // {
        //   title: '服务费率',
        //   dataIndex: 'feeRate',
        //   scopedSlots: { customRender: 'feeRate' }
        // },
        {
          title: '供应商费率',
          dataIndex: 'feeRate',
          scopedSlots: { customRender: 'feeRate' },
          width: '120px'
        },
        {
          title: '在线支付',
          dataIndex: 'isOpenXbd',
          scopedSlots: { customRender: 'isOpenXbd' }
        },
        //{
          //title: '计算方式',
         // dataIndex: 'feeMode',
          //scopedSlots: { customRender: 'feeMode' }
       // },
        {
          title: '企业状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        // {
        //   title: '管理员姓名',
        //   dataIndex: 'managerName'
        // },
        // {
        //   title: '管理员电话',
        //   dataIndex: 'managerPhone'
        // },
        {
          title: '创建时间',
          dataIndex: 'createdTime',
          scopedSlots: { customRender: 'createdTime' }
        },
        // {
        //   title: '运营人员',
        //   dataIndex: 'operationsManagerName'
        // },
        // {
        //   title: '销售人员',
        //   dataIndex: 'salesName'
        // },
        // {
        //   title: '风险星级',
        //   dataIndex: 'riskStar',
        //   align:'center'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          width: '265px',
          scopedSlots: { customRender: 'action' },
          fixed: 'right'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        let filterParams = this.queryParam
        if (this.queryParam.createdTime) {
          filterParams = Object.assign({}, this.queryParam, {
            startTime: `${this.queryParam.createdTime[0]} 00:00:00`,
            endTime: `${this.queryParam.createdTime[1]} 23:59:59`
          })
        }
        delete filterParams.createdTime
        console.log(filterParams)
        return getEnterpriseList(Object.assign(parameter, filterParams)).then(res => {
          return res.resData
        })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false,
      freezing: false,
      feeRateRangeList: [],
      feeRateRangeColumns: [
        {
          title: '最低金额',
          dataIndex: 'amountLow',
          scopedSlots: { customRender: 'money' }
        },
        {
          title: '最高金额',
          dataIndex: 'amountHigh',
          scopedSlots: { customRender: 'money' }
        },
        {
          title: '服务费率',
          dataIndex: 'feeRate',
          scopedSlots: { customRender: 'rate' }
        }
      ],
      feeRateVisible: false,
      // enterpriseServerFeeRateList: [],
      enterpriseServerFeeRateList:[],
      gnflVisible: false,
      FeeRateColumns: [
        {
          title: '供应商名称',
          dataIndex: 'serverName',
          width: '120px'
        },
        {
          title: '账单方式',
          dataIndex: 'feeMode',
          scopedSlots: { customRender: 'feeMode' },
          width: '100px'
        },
        {
          title: '费率类型',
          dataIndex: 'feeRateType',
          scopedSlots: { customRender: 'feeRateType' },
          width: '100px'
        },
        {
          title: '服务费率',
          dataIndex: 'feeRate',
          scopedSlots: { customRender: 'feeRate' },
          width: '100px'
        },
        {
          title: '税率',
          dataIndex: 'taxRate',
          scopedSlots: { customRender: 'taxRate' },
          width: '100px'
        },
        // {
        //   title: '薪八达合同uuid',
        //   dataIndex: 'xbdContractUuid',
        //   width: '100px'
        // }
      ],
      showJieti: false,
      feeRateGuList: []
    }
  },
  created() {
    // this.tableOption()
    // getRoleList({ t: new Date() })
  },
  methods: {
    change(value) {
      if (value === undefined) {
        this.queryParam = {}
      }
    },
    handleEdit(record) {
      this.$router.push({
        name: 'EnterpriseEdit',
        params: {
          enterpriseId: record.enterpriseId
        }
      })
    },
    handleSub(record) {
      if (this.freezing) {
        return
      }
      const type = record.status === 0 ? '解冻' : '冻结'
      this.freezing = true
      freezeEnterprise({
        enterpriseId: record.enterpriseId,
        isFreeze: Boolean(record.status)
      })
        .then(res => {
          this.$refs.table.refresh()
          this.$message.success(`${record.enterpriseName}${type}成功`)
        })
        .finally(() => {
          this.freezing = false
        })
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    showFeeRate(record) {
      this.enterpriseServerFeeRateList = []
        if (record.enterpriseServerFeeRateList.length > 0) {
          record.enterpriseServerFeeRateList.forEach(i => {
            console.log(i)
            // return
          getServerFeeList({serverId:i.serverId}).then(res => {
              const obj = {
                serverName: res.resData.serverName,
                feeMode: i.feeMode,
                feeRateType: 1,
                serverId: i.serverId,
                feeRate: parseFloat((i.feeRate * 100).toFixed(10)),
                taxRate: i.taxRate,
                // xbdContractUuid: ''
              }
              // if (i.xbdContractUuid) {
              //   obj.xbdContractUuid = i.xbdContractUuid
              // }
              this.enterpriseServerFeeRateList.push(obj)
            })
          })
        }
        // this.feeRateRangeList = data.feeRateRangeList || []
        this.rangeRateVos = []
        var map = {}
        var dest = []
        if (record.feeRateRangeList.length > 0) {
          // for(var i = 0; i < record.feeRateRangeList.length; i++){
          //   var ai = record.feeRateRangeList[i]
          //   if(!map[ai.serverId]){
          //       dest.push({
          //             serverId: ai.serverId,
          //             serverName: '',
          //             feeMode: ai.feeMode,
          //             feeRateType: 2,
          //             feeRateList: [ai],
          //             taxRate: ai.taxRate,
          //             // xbdContractUuid: ai.xbdContractUuid || ''
          //         })
          //         map[ai.serverId] = ai
               
          //   }else{
          //       for(var j = 0; j < dest.length; j++){
          //           const dj = dest[j]
          //           if(dj.serverId == ai.serverId){
          //               dj.feeRateList.push(ai)
          //               break
          //           }
          //       }
          //   }
          // }
          const dataArr = []
            record.feeRateRangeList.map(mapItem => {
              if (dataArr.length == 0) {
                // date: mapItem.date, List: [mapItem]
                  dataArr.push({ 
                    serverId: mapItem.serverId,
                    serverName: '',
                    feeRateType: 2,
                    feeRate: mapItem.feeRate,
                    taxRate: mapItem.taxRate,
                    xbdContractUuid: '',
                    feeMode: mapItem.feeMode,
                    feeRateList: [mapItem]
                  })
              } else {
                const res = dataArr.some(item=> {//判断相同日期，有就添加到当前项
                  if (item.taxRate == mapItem.taxRate && item.serverId == mapItem.serverId) {
                    item.feeRateList.push(mapItem)
                    return true
                  }
                })
                console.log(dataArr)
                console.log(res)
                if (!res) {//如果没找相同日期添加一个新对象
                  dataArr.push({ 
                    serverId: mapItem.serverId,
                    serverName: '',
                    feeRateType: 2,
                    feeRate: mapItem.feeRate,
                    taxRate: mapItem.taxRate,
                    xbdContractUuid: mapItem.xbdContractUuid,
                    feeMode: mapItem.feeMode,
                    feeRateList: [mapItem]
                  })
                }
              }
            })
            // console.log(this.feeRateFixList)
            // this.feeRateFixList = [...this.feeRateFixList, ...dataArr]
            dest = dataArr
        }
        // console.log(...dest)
        dest.forEach((i,index) => {
           getServerFeeList({serverId:i.serverId}).then(res => {
                  const serverName = res.resData.serverName
                  dest[index].serverName = serverName
                })
        })
        // console.log(dest[0])
        // return
        // this.feeRateRangeList = dest
        this.enterpriseServerFeeRateList = [...this.enterpriseServerFeeRateList, ...dest]
        this.gnflVisible = true
      // this.feeRateVisible = true
    },

    resetLoginPassword(record) {
      resetLoginPassword(record.enterpriseId)
      try {
        this.$refs.table.refresh()
        this.$message.success('密码重置成功')
      } catch (e) {
        this.$message.error('重置失败请联系管理员')
      }
    },
    resetPayPasswords (record) {
      resetPayPassword(record.enterpriseId)
      try {
        this.$refs.table.refresh()
        this.$message.success('密码重置成功')
      } catch (e) {
        this.$message.error('重置失败请联系管理员')
      }
    },
    gotoNewPage(record){
      const { enterpriseSimpleName, token} = record
      window.open(`http://saas.xinyonggong.com/index?appId=admin&enterpriseSimpleName=${enterpriseSimpleName}&token=${token}`,'_blank')
    }
  }
}
</script>
